<!--自动匹配下拉编辑框-->
<template>
    <el-select
        :ref="params.column.colDef.field + '_' + params.rowIndex"
        v-model="value"
        default-first-option
        filterable
        remote
        :remote-method="remoteMethod"
        :loading="loading"
        :placeholder="autoFilterSelectProp.placeholder"
        :value-key="autoFilterSelectProp.valueKey"
        @keydown.native="handleKeydown"
        @change="onChange">
            <el-option
                v-for="(item, index) in optionList"
                :key="index"
                :label="item[autoFilterSelectProp.optionLabel]"
                :value="item">
            </el-option>
    </el-select>
</template>
<script>
import Vue from 'vue'
import { Select, Option } from 'element-ui'
Vue.use(Select)
Vue.use(Option)
import {autoFilterMethod} from '@/api/system/table'

const defaultProp = {
    valueKey: 'value',
    optionLabel: 'label',
    optionValue: 'value',
    methodName: '',
    placeholder: '',
    rules: [],
    wmsDataBaseParams: {},
    queryLength: 1,
}

export default Vue.extend({
    name: 'AutoFilterSelectEditor',
    data() {
        return {
            loading: false,
            value: {},
            autoFilterSelectProp: Object.assign({}, defaultProp),
            optionList: []
        }
    },
    beforeMount() {
        this.autoFilterSelectProp = Object.assign({}, defaultProp, this.params.column.colDef.cellEditorParams || {});
        this.value = Object.assign({}, this.params.data[this.params.column.colDef.field + 'Obj']);
        if(this.isResultEmpty(this.value)){
            this.optionList = [];
        }else{
            this.optionList = [Object.assign({}, this.value)];
        }
    },
    mounted() {
        setTimeout(() => {
            this.$refs[this.params.column.colDef.field + '_' + this.params.rowIndex] && this.$refs[this.params.column.colDef.field + '_' + this.params.rowIndex].focus()
        }, 0);
    },
    methods: {
        // 远程搜索
        remoteMethod(query){
            if (query && query.length >= this.autoFilterSelectProp.queryLength) {
                let submitData = {};
                if (_.isFunction(this.autoFilterSelectProp.wmsDataBaseParams)) {
                    submitData = Object.assign({}, this.autoFilterSelectProp.wmsDataBaseParams());
                }
                submitData.params = query
                this.loading = true;
                autoFilterMethod[this.autoFilterSelectProp.methodName].call(null, submitData).then(res => {
                    this.optionList = Object.assign([], res.rows)
                    this.loading = false;
                }).catch(() => {
                    this.loading = false;
                })
            }else{
                this.optionList = []
            }
        },
        handleKeydown(event) {
            let KEY_LEFT = 37,
                KEY_UP = 38,
                KEY_RIGHT = 39,
                KEY_DOWN = 40,
                KEY_PAGE_UP = 33,
                KEY_PAGE_DOWN = 34,
                KEY_PAGE_HOME = 36,
                KEY_PAGE_END = 35,
                KEY_ENTER = 13,
                KEY_TAB = 9;

            let keyCode = event.keyCode;

            // let isNavigationKey = keyCode===KEY_LEFT || keyCode===KEY_RIGHT || keyCode===KEY_UP
            // || keyCode===KEY_DOWN || keyCode===KEY_PAGE_DOWN || keyCode===KEY_PAGE_UP
            // || keyCode===KEY_PAGE_HOME || keyCode===KEY_PAGE_END;

            // if (isNavigationKey) {
            //     event.stopPropagation();
            // }

            // 光标跳转
            if(keyCode === KEY_TAB || keyCode === KEY_ENTER){
                let {rowIndex, colKey, floating} = this.params.api.getFocusedCell();
                this.tabToNext({rowIndex, colKey, floating});
                event.stopPropagation();
            }
        },
        tabToNext({rowIndex, colKey, floating}) {
            let columnDefs = this.params.columnApi.getAllColumns();
            let rowTotal = this.params.api.getLastDisplayedRow();
            let rowPinned = this.params.column.colDef.pinned;
            let tabindex = this.params.tabindex || -1;
            let sameLineFlag = false;

            tabindex = tabindex + 1;
            for(let i = 0; i < columnDefs.length; i++){
                let tmpColDef = columnDefs[i].colDef;
                if(tmpColDef.cellEditorParams && tmpColDef.cellEditorParams.tabindex === tabindex){
                    sameLineFlag = true;
                    colKey = columnDefs[i].colId;
                    rowPinned = tmpColDef.pinned;
                    break;
                }
            }
            if(!sameLineFlag){
                rowIndex++;
                tabindex = 1;
                let tmpCol = columnDefs.filter(obj => obj.colDef && obj.colDef.cellEditorParams && obj.colDef.cellEditorParams.tabindex === 1)[0];
                colKey = tmpCol.colId;
                rowPinned = tmpCol.colDef && tmpCol.colDef.pinned;
            }
            if(rowIndex <= rowTotal){
                this.params.api.setFocusedCell(rowIndex, colKey);
                this.params.api.startEditingCell({
                    rowIndex: rowIndex,
                    colKey: colKey,
                    rowPinned: rowPinned
                });
            }
        },
        onChange(value) {
            this.value = value;
            this.handelDataDeal();
            this.params.api.redrawRows();
            setTimeout(() => {
                let rowIndex = this.params.rowIndex;
                let colKey = this.params.column.colDef.field;
                let floating = null;
                this.tabToNext({rowIndex, colKey, floating});
            }, 0);
        },
        handelDataDeal() {
            if (_.isFunction(this.autoFilterSelectProp.dataDeal)) {
                this.params.data[this.params.column.colDef.field] = this.value[this.autoFilterSelectProp.optionLabel] || '';
                this.params.data[this.params.column.colDef.field + 'Obj'] = Object.assign({}, this.value);
                let res = this.autoFilterSelectProp.dataDeal(this.value, this.params.data, this.params);
            }
        },
        getValue() {
            this.handelDataDeal();
            let valid = this.validateCell(this.params.data, this.value[this.autoFilterSelectProp.optionLabel], this.autoFilterSelectProp.rules) || {};
            let tmpValid = this.params.data.tmsValid || [];
            if(tmpValid.some(obj => obj.rowIndex === this.params.rowIndex && obj.colKey === this.params.column.colId)){
                tmpValid.map(obj => {
                    if(obj.rowIndex === this.params.rowIndex && obj.colKey === this.params.column.colId){
                        obj.tmsError = valid.tmsError || false;
                        obj.tmsErrorMessage = valid.tmsErrorMessage || '';
                    }
                    return obj;
                })
            }else{
                tmpValid.push({
                    rowIndex: this.params.rowIndex,
                    colKey: this.params.column.colId,
                    tmsError: valid.tmsError || false,
                    tmsErrorMessage: valid.tmsErrorMessage || ''
                })
            }
            this.params.data.tmsValid = tmpValid;
            return this.value[this.autoFilterSelectProp.optionLabel] || '';
        }
    }
})
</script>